﻿using System.Collections.Generic;

namespace Miao
{
    /// <summary>
    /// 表示一个等差数列
    /// </summary>
    public readonly struct ArithmeticProgression : IArithmeticProgression<float, Range>
    {
        public float first { get; }
        public float commonDifference { get; }

        public float this[int index] => first + commonDifference * index;

        public static ArithmeticProgression Create(float min, float max, int internvalCount)
        {
            return new ArithmeticProgression(min, (max - min) / internvalCount);
        }

        public ArithmeticProgression(float first, float commonDifference)
        {
            this.first = first;
            this.commonDifference = commonDifference;
        }

        public Range GetInterval(int index)
        {
            float min = this[index];
            return new Range(min, min + commonDifference);
        }
        public float GetClosestTerm(float value)
        {
            int intervalIndex = GetIntervalIndex(value);
            float result = intervalIndex * commonDifference;
            float remainder = value % commonDifference;
            return remainder < commonDifference * 0.5f ? result : result + commonDifference;
        }
        public int GetTermIndex(float value)
        {
            int intervalIndex = GetIntervalIndex(value);
            float remainder = value % commonDifference;
            return remainder < commonDifference * 0.5f ? intervalIndex : (intervalIndex + 1);
        }
        public int GetIntervalIndex(float value)
        {
            return (int)(value / commonDifference);
        }

        public float[] ToArray(int length)
        {
            float[] result = new float[length];
            for (int i = 0; i < length; i++) result[i] = this[i];
            return result;
        }
        public void ToArray(float[] result, int length)
        {
            for (int i = 0; i < length; i++) result[i] = this[i];
        }
        public void ToList(IList<float> result, int length)
        {
            for (int i = 0; i < length; i++) result.Add(this[i]);
        }
    }
}
